﻿
#include "EasyTcpClient.hpp"

#include <thread>

#include <sstream>

const unsigned short SERVER_PORT = 4444;

void cmdThread(EasyTcpClient* client)
{
    int nret = 0;
    char cmdBuf[128];

    printf("cmdThread线程已进入...\n");
    if (client == NULL) {
        printf("线程参数为NULL!!\n");
        return;
    }

    while (true)
    {
        cmdBuf[0] = '\0';
        scanf("%s", cmdBuf);

        if (0 == stricmp(cmdBuf, "exit")) {
            char cmd[] = "exit";
            //nret = client->sendData((unsigned char*)cmd, sizeof(cmd));
            client->close();
            break;
        }
        else {
            
            MessageBuildHelper mbh;
            CTextMessage ctm;

            ctm.str = cmdBuf;
            TextMessage *ttm = ctm.serialize();

            int bufLen = mbh.getMessageLength((DataHead*)ttm);

            nret = client->sendData((char*)ttm, bufLen);
            if (nret < 0) {
                myprintf("向服务器发送失败!");
            }
        }
        if (SOCKET_ERROR == nret)
        {
            printf("发送失败.\n");
            break;
        }
    }
}

int main(int argc, char* argv[])
{
    int nret = 0;
    EasyTcpClient client;

    do
    {
        EasyTcpClient::LoadSocket();

        client.InitSocket();
        
        const char* ip = "127.0.0.1";
        client.connectTo(ip, SERVER_PORT);


        

#if 1
        // 注意该对象析构时，会调用 abort()
        std::thread t(cmdThread, &client);
        t.detach();
        while (client.isRunning())
        {
            client.onRun();
        }
#else

        MessageBuildHelper mbh;
        CTextMessage ctm;

        std::stringstream ss;

        ss << "噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢噢";
        ss << ss.str();
        ss << ss.str();
        ss << ss.str();
        ss << ss.str();
        //ss << ss.str();
        //ss << ss.str();
        //ss << ss.str();
        //ss << ss.str();
        //ss << ss.str();

        ctm.str = ss.str();
        TextMessage *ttm = ctm.serialize();

        long long times = 0;

        while (client.isRunning())
        {
            times++;
            myprintf("向服务器发送消息，第 %lld 次", times);

            int bufLen = mbh.getMessageLength((DataHead*)ttm);
            nret = client.sendData((char*)ttm, bufLen);
            if (nret < 0) {
                myprintf("向服务器发送失败!");
            }
        }
#endif // 1


        getchar();
    } while (0);

    client.close();

    EasyTcpClient::UnloadSocket();

    printf("程序退出...\n");
    getchar();
    return 0;
}

